{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "PxHrg4Cjuapm"
   },
   "source": [
    "# Distributed arrays and automatic parallelization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pFtQjv4SzHRj"
   },
   "source": [
    "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google/jax/blob/main/docs/notebooks/Distributed_arrays_and_automatic_parallelization.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://kaggle.com/kernels/welcome?src=https://github.com/google/jax/blob/main/docs/notebooks/Distributed_arrays_and_automatic_parallelization.ipynb)\n",
    "\n",
    "This tutorial discusses parallelism via `jax.Array`, the unified array object model available in JAX v0.4.1 and newer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "FNxScTfq3vGF"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import functools\n",
    "from typing import Optional\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "import jax\n",
    "import jax.numpy as jnp"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "eyHMwyEfQJcz"
   },
   "source": [
    "⚠️ WARNING: The notebook requires 8 devices to run."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "IZMLqOUV3vGG"
   },
   "outputs": [],
   "source": [
    "if len(jax.local_devices()) < 8:\n",
    "  raise Exception(\"Notebook requires 8 devices to run\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3f37ca93"
   },
   "source": [
    "## Intro and a quick example\n",
    "\n",
    "By reading this tutorial notebook, you'll learn about `jax.Array`, a unified\n",
    "datatype for representing arrays, even with physical storage spanning multiple\n",
    "devices. You'll also learn about how using `jax.Array`s together with `jax.jit`\n",
    "can provide automatic compiler-based parallelization.\n",
    "\n",
    "Before we think step by step, here's a quick example.\n",
    "First, we'll create a `jax.Array` sharded across multiple devices:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Gf2lO4ii3vGG"
   },
   "outputs": [],
   "source": [
    "from jax.experimental import mesh_utils\n",
    "from jax.sharding import PositionalSharding"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "q-XBTEoy3vGG"
   },
   "outputs": [],
   "source": [
    "# Create a Sharding object to distribute a value across devices:\n",
    "sharding = PositionalSharding(mesh_utils.create_device_mesh((8,)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "vI39znW93vGH",
    "outputId": "3b518df8-5c29-4848-acc3-e41df939f30b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n"
     ]
    }
   ],
   "source": [
    "# Create an array of random values:\n",
    "x = jax.random.normal(jax.random.key(0), (8192, 8192))\n",
    "# and use jax.device_put to distribute it across devices:\n",
    "y = jax.device_put(x, sharding.reshape(4, 2))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "jZ0ZY9Um9Jg4"
   },
   "source": [
    "Next, we'll apply a computation to it and visualize how the result values are\n",
    "stored across multiple devices too:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "-qCnHZl83vGI",
    "outputId": "9da9c29e-ce88-4425-e1ec-e93e5bcf3106"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n"
     ]
    }
   ],
   "source": [
    "z = jnp.sin(y)\n",
    "jax.debug.visualize_array_sharding(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5qccVQoE9tEi"
   },
   "source": [
    "The evaluation of the `jnp.sin` application was automatically parallelized\n",
    "across the devices on which the input values (and output values) are stored:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "_VTzN0r03vGI",
    "outputId": "c9208010-984b-442b-d105-c8c6a3a010e6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The slowest run took 13.32 times longer than the fastest. This could mean that an intermediate result is being cached \n",
      "5 loops, best of 5: 9.69 ms per loop\n"
     ]
    }
   ],
   "source": [
    "# `x` is present on a single device\n",
    "%timeit -n 5 -r 5 jnp.sin(x).block_until_ready()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "QuzhU1g63vGI",
    "outputId": "d48fc76e-79a7-47b9-d392-b18a1c33c798"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 loops, best of 5: 1.86 ms per loop\n"
     ]
    }
   ],
   "source": [
    "# `y` is sharded across 8 devices.\n",
    "%timeit -n 5 -r 5 jnp.sin(y).block_until_ready()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xWknFQbQ-bzV"
   },
   "source": [
    "Now let's look at each of these pieces in more detail!\n",
    "\n",
    "\n",
    "## `Sharding` describes how array values are laid out in memory across devices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "W6HsXauGxL6w"
   },
   "source": [
    "### Sharding basics, and the `PositionalSharding` subclass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "NWDyp_EjVHkg"
   },
   "source": [
    "To parallelize computation across multiple devices, we first must lay out input data across multiple devices.\n",
    "\n",
    "In JAX, `Sharding` objects describe distributed memory layouts. They can be used with `jax.device_put` to produce a value with distributed layout.\n",
    "\n",
    "For example, here's a value with a single-device `Sharding`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "VmoX4SUp3vGJ"
   },
   "outputs": [],
   "source": [
    "import jax\n",
    "x = jax.random.normal(jax.random.key(0), (8192, 8192))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "vNRabO2J3vGJ",
    "outputId": "73db7b6e-c2e7-467d-a0ef-c35e29e582dd"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────────────────┐\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│         TPU 0         │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "jax.debug.visualize_array_sharding(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "HhCjhK0zXIqX"
   },
   "source": [
    "Here, we're using the `jax.debug.visualize_array_sharding` function to show where the value `x` is stored in memory. All of `x` is stored on a single device, so the visualization is pretty boring!\n",
    "\n",
    "But we can shard `x` across multiple devices by using `jax.device_put` and a `Sharding` object. First, we make a `numpy.ndarray` of `Devices` using `mesh_utils.create_device_mesh`, which takes hardware topology into account for the `Device` order:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "VUIEIzRp3vGK"
   },
   "outputs": [],
   "source": [
    "from jax.experimental import mesh_utils\n",
    "devices = mesh_utils.create_device_mesh((8,))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lbOKFWmBX1iv"
   },
   "source": [
    "Then, we create a `PositionalSharding` and use it with `device_put`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "jwrWfZeB3vGK",
    "outputId": "e6f126bd-f6bd-48c7-c130-6f02757e3342"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────────────────┐\n",
      "│         TPU 0         │\n",
      "├───────────────────────┤\n",
      "│         TPU 1         │\n",
      "├───────────────────────┤\n",
      "│         TPU 2         │\n",
      "├───────────────────────┤\n",
      "│         TPU 3         │\n",
      "├───────────────────────┤\n",
      "│         TPU 6         │\n",
      "├───────────────────────┤\n",
      "│         TPU 7         │\n",
      "├───────────────────────┤\n",
      "│         TPU 4         │\n",
      "├───────────────────────┤\n",
      "│         TPU 5         │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "from jax.sharding import PositionalSharding\n",
    "\n",
    "sharding = PositionalSharding(devices)\n",
    "\n",
    "x = jax.device_put(x, sharding.reshape(8, 1))\n",
    "jax.debug.visualize_array_sharding(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "TUu69IWXZdTm"
   },
   "source": [
    "Here `sharding` is a `PositionalSharding` which acts like an array with sets of devices as elements:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "zxWB82Kz3vGK",
    "outputId": "11384a6b-fabc-4c4c-bcad-a3be51eb0465"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PositionalSharding([{TPU 0} {TPU 1} {TPU 2} {TPU 3} {TPU 6} {TPU 7} {TPU 4} {TPU 5}])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sharding"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "uRLpOcmNj_Vt"
   },
   "source": [
    "The device numbers here are not in numerical order, because the mesh reflects the underlying toroidal topology of the device.\n",
    "\n",
    "By writing `PositionalSharding(ndarray_of_devices)`, we fix the device order and the initial shape. Then we can reshape it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "PLsnpSzc3vGL",
    "outputId": "9f4db733-cafe-46ae-c057-dc31046a6f66"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PositionalSharding([[{TPU 0}]\n",
       "                    [{TPU 1}]\n",
       "                    [{TPU 2}]\n",
       "                    [{TPU 3}]\n",
       "                    [{TPU 6}]\n",
       "                    [{TPU 7}]\n",
       "                    [{TPU 4}]\n",
       "                    [{TPU 5}]])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sharding.reshape(8, 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "iqKdI4LO3vGL",
    "outputId": "6aa10fc2-cec4-4401-a0df-343e71646e0a"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PositionalSharding([[{TPU 0} {TPU 1}]\n",
       "                    [{TPU 2} {TPU 3}]\n",
       "                    [{TPU 6} {TPU 7}]\n",
       "                    [{TPU 4} {TPU 5}]])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sharding.reshape(4, 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KBu6WLfhm7ra"
   },
   "source": [
    "To use `device_put` with a data array `x`, we can reshape the `sharding` into a shape that is _congruent_ with `x.shape`, meaning a shape with the same length as `x.shape` and where each element evenly divides the corresponding element of `x.shape`:\n",
    "```python\n",
    "def is_congruent(x_shape: Sequence[int], sharding_shape: Sequence[int]) -> bool:\n",
    "  return (len(x_shape) == len(sharding_shape) and\n",
    "          all(d1 % d2 == 0 for d1, d2 in zip(x_shape, sharding_shape)))\n",
    "```\n",
    "\n",
    "For example, we can reshape `sharding` to have shape `(4, 2)`, then use it in a `device_put`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "SELr4xNi3vGL",
    "outputId": "b2f4acec-0cd3-4829-ca16-cae2e0e8ca60"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PositionalSharding([[{TPU 0} {TPU 1}]\n",
      "                    [{TPU 2} {TPU 3}]\n",
      "                    [{TPU 6} {TPU 7}]\n",
      "                    [{TPU 4} {TPU 5}]])\n"
     ]
    }
   ],
   "source": [
    "sharding = sharding.reshape(4, 2)\n",
    "print(sharding)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8IVIsqfX3vGL",
    "outputId": "033d0e02-a643-4f4c-9d24-9cd8465bc69a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, sharding)\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tyg9F-UIsU__"
   },
   "source": [
    "Here `y` represents the same _value_ as `x`, but its shards (i.e. slices) are stored in different devices' memories.\n",
    "\n",
    "Different `PositionalSharding` shapes result in different distributed layouts (i.e. shardings) of the result:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "cCjt6QCz3vGM",
    "outputId": "4ad8a611-596d-424f-b6c5-fc00f1adc306"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PositionalSharding([[{TPU 0} {TPU 1} {TPU 2} {TPU 3} {TPU 6} {TPU 7} {TPU 4} {TPU 5}]])\n"
     ]
    }
   ],
   "source": [
    "sharding = sharding.reshape(1, 8)\n",
    "print(sharding)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "yTK4Nz3u3vGM",
    "outputId": "e445c6bc-4fe3-4e9d-cc9e-d82858f58312"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐\n",
      "│       │       │       │       │       │       │       │       │\n",
      "│       │       │       │       │       │       │       │       │\n",
      "│       │       │       │       │       │       │       │       │\n",
      "│       │       │       │       │       │       │       │       │\n",
      "│ TPU 0 │ TPU 1 │ TPU 2 │ TPU 3 │ TPU 6 │ TPU 7 │ TPU 4 │ TPU 5 │\n",
      "│       │       │       │       │       │       │       │       │\n",
      "│       │       │       │       │       │       │       │       │\n",
      "│       │       │       │       │       │       │       │       │\n",
      "│       │       │       │       │       │       │       │       │\n",
      "└───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, sharding)\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0PuamOvXubcf"
   },
   "source": [
    "In some cases, we don't just want to store each slice of `x` in a single device's memory; we might want to _replicate_ some slices, meaning storing copies of a slice's values in multiple devices' memories.\n",
    "\n",
    "With `PositionalSharding`, we can express replication by calling the reducer method `replicate`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "_jr6XYKx3vGM",
    "outputId": "59c8b9a4-b8af-493a-ba8d-da5931e88f93"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PositionalSharding([[{TPU 0, 2, 4, 6} {TPU 1, 3, 5, 7}]])\n"
     ]
    }
   ],
   "source": [
    "sharding = sharding.reshape(4, 2)\n",
    "print(sharding.replicate(axis=0, keepdims=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "S5vzjFuH3vGN",
    "outputId": "b6ce2675-7261-4e57-fa8c-b4e87abf7e52"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────┬───────────┐\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│TPU 0,2,4,6│TPU 1,3,5,7│\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "└───────────┴───────────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, sharding.replicate(axis=0, keepdims=True))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "FzeP0kpTvJv-"
   },
   "source": [
    "Here the visualization shows that `x` is sharded two ways along its second dimension (and not sharded along the first dimension), and each of those shards is replicated four ways (i.e. stored in four device memories).\n",
    "\n",
    "The `replicate` method is analogous to the familiar NumPy array reduction methods like `.sum()` and `.prod()`. It operates along an axis performing a set union. So if `sharding` has shape `(4, 2)`, then `sharding.replicate(0, keepdims=True)` has shape `(1, 2)`, and `sharding.replicate(1, keepdims=True)` has shape `(4, 1)`. Unlike analogous NumPy methods, `keepdims=True` is actually the default, so reduced-over axes aren't squeezed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "DR7VV-6e3vGN",
    "outputId": "f879fc2c-5723-4199-b306-295bc1b3681e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 2)\n",
      "(4, 1)\n"
     ]
    }
   ],
   "source": [
    "print(sharding.replicate(0).shape)\n",
    "print(sharding.replicate(1).shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "agUtVUVx3vGN",
    "outputId": "0e9789ef-ce52-4ed6-8bd5-c876b95f66e6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────────────────┐\n",
      "│        TPU 0,1        │\n",
      "├───────────────────────┤\n",
      "│        TPU 2,3        │\n",
      "├───────────────────────┤\n",
      "│        TPU 6,7        │\n",
      "├───────────────────────┤\n",
      "│        TPU 4,5        │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, sharding.replicate(1))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "D31t5POXxHHJ"
   },
   "source": [
    "### `NamedSharding` gives a way to express shardings with names"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ayMKWeTmxl-X"
   },
   "source": [
    "So far we've worked with `PositionalSharding`, but there are alternative ways to express shardings. In fact, `Sharding` is an interface, and any class that implements that interface can be used with functions like `device_put`.\n",
    "\n",
    "Another convenient way to express sharding is with the `NamedSharding`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "zpB1JxyK3vGN",
    "outputId": "46d5da37-840c-49d8-8380-a162811bae8a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n"
     ]
    }
   ],
   "source": [
    "from jax.sharding import Mesh\n",
    "from jax.sharding import PartitionSpec\n",
    "from jax.sharding import NamedSharding\n",
    "from jax.experimental import mesh_utils\n",
    "\n",
    "P = PartitionSpec\n",
    "\n",
    "devices = mesh_utils.create_device_mesh((4, 2))\n",
    "mesh = Mesh(devices, axis_names=('a', 'b'))\n",
    "y = jax.device_put(x, NamedSharding(mesh, P('a', 'b')))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OW_Cc92G1-nr"
   },
   "source": [
    "We can define a helper function to make things simpler:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8g0Md2Gd3vGO"
   },
   "outputs": [],
   "source": [
    "devices = mesh_utils.create_device_mesh((4, 2))\n",
    "default_mesh = Mesh(devices, axis_names=('a', 'b'))\n",
    "\n",
    "def mesh_sharding(\n",
    "    pspec: PartitionSpec, mesh: Optional[Mesh] = None,\n",
    "  ) -> NamedSharding:\n",
    "  if mesh is None:\n",
    "    mesh = default_mesh\n",
    "  return NamedSharding(mesh, pspec)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "zp3MfS4Y3vGO",
    "outputId": "2c2f7201-c2c1-49e5-f8a5-0730c124d89a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, mesh_sharding(P('a', 'b')))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xZ88riVm1mv5"
   },
   "source": [
    "Here, we use `P('a', 'b')` to express that the first and second axes of `x` should be sharded over the device mesh axes `'a'` and `'b'`, respectively. We can easily switch to `P('b', 'a')` to shard the axes of `x` over different devices:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "FigK5Zsa3vGO",
    "outputId": "eca784e8-33fe-4e9b-a41d-21e9ee781a35"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────┬───────┬───────┬───────┐\n",
      "│       │       │       │       │\n",
      "│ TPU 0 │ TPU 2 │ TPU 6 │ TPU 4 │\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "├───────┼───────┼───────┼───────┤\n",
      "│       │       │       │       │\n",
      "│ TPU 1 │ TPU 3 │ TPU 7 │ TPU 5 │\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "└───────┴───────┴───────┴───────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, mesh_sharding(P('b', 'a')))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "hI-HD0xN3vGO",
    "outputId": "c3e7dc3c-4048-448a-ef0b-50683532fcdc"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────────────────┐\n",
      "│        TPU 0,1        │\n",
      "├───────────────────────┤\n",
      "│        TPU 2,3        │\n",
      "├───────────────────────┤\n",
      "│        TPU 6,7        │\n",
      "├───────────────────────┤\n",
      "│        TPU 4,5        │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "# This `None` means that `x` is not sharded on its second dimension,\n",
    "# and since the Mesh axis name 'b' is not mentioned, shards are\n",
    "# replicated across it.\n",
    "y = jax.device_put(x, mesh_sharding(P('a', None)))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "AqcAsNUgXCZz"
   },
   "source": [
    "Here, because `P('a', None)` doesn't mention the `Mesh` axis name `'b'`, we get replication over the axis `'b'`. The `None` here is just acting as a placeholder to line up against the second axis of the value `x`, without expressing sharding over any mesh axis. (As a shorthand, trailing `None`s can be omitted, so that `P('a', None)` means the same thing as `P('a')`. But it doesn't hurt to be explicit!)\n",
    "\n",
    "To shard only over the second axis of `x`, we can use a `None` placeholder in the `PartitionSpec`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "EXBExMQC3vGP",
    "outputId": "fe1c8d7e-3345-4438-b9d2-780e7854b4eb"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────┬───────────┐\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│TPU 0,2,4,6│TPU 1,3,5,7│\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "└───────────┴───────────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, mesh_sharding(P(None, 'b')))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "PjUpG8uz3vGP",
    "outputId": "64d8224d-15d9-4ad4-d613-f7f85b1dc1af"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────┬───────┬───────┬───────┐\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "│TPU 0,1│TPU 2,3│TPU 6,7│TPU 4,5│\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "└───────┴───────┴───────┴───────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, mesh_sharding(P(None, 'a')))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "--AZgW1P3HFT"
   },
   "source": [
    "For a fixed mesh, we can even partition one logical axis of `x` over multiple device mesh axes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "fVcPbDUA3vGP",
    "outputId": "7f524ba5-a6d8-4490-cda9-685ad11416f9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────────────────┐\n",
      "│         TPU 0         │\n",
      "├───────────────────────┤\n",
      "│         TPU 1         │\n",
      "├───────────────────────┤\n",
      "│         TPU 2         │\n",
      "├───────────────────────┤\n",
      "│         TPU 3         │\n",
      "├───────────────────────┤\n",
      "│         TPU 6         │\n",
      "├───────────────────────┤\n",
      "│         TPU 7         │\n",
      "├───────────────────────┤\n",
      "│         TPU 4         │\n",
      "├───────────────────────┤\n",
      "│         TPU 5         │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, mesh_sharding(P(('a', 'b'), None)))\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "c1tTFudr3Ae7"
   },
   "source": [
    "Using `NamedSharding` makes it easy to define a device mesh once and give its axes names, then just refer to those names in `PartitionSpec`s for each `device_put` as needed."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rhWzHgGf4mkg"
   },
   "source": [
    "## Computation follows data sharding and is automatically parallelized"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JukoaRhl4tXJ"
   },
   "source": [
    "With sharded input data, the compiler can give us parallel computation. In particular, functions decorated with `jax.jit` can operate over sharded arrays without copying data onto a single device. Instead, computation follows sharding: based on the sharding of the input data, the compiler decides shardings for intermediates and output values, and parallelizes their evaluation, even inserting communication operations as necessary.\n",
    "\n",
    "For example, the simplest computation is an elementwise one:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "_EmQwggc3vGQ"
   },
   "outputs": [],
   "source": [
    "from jax.experimental import mesh_utils\n",
    "from jax.sharding import PositionalSharding\n",
    "sharding = PositionalSharding(mesh_utils.create_device_mesh((8,)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "LnT0vWjc3vGQ",
    "outputId": "8089effc-aa4c-49e3-dd19-7064881dbad0"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input sharding:\n",
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n",
      "output sharding:\n",
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n"
     ]
    }
   ],
   "source": [
    "x = jax.device_put(x, sharding.reshape(4, 2))\n",
    "print('input sharding:')\n",
    "jax.debug.visualize_array_sharding(x)\n",
    "\n",
    "y = jnp.sin(x)\n",
    "print('output sharding:')\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "7tY2gVRfazaT"
   },
   "source": [
    "Here for the elementwise operation `jnp.sin` the compiler chose the output sharding to be the same as the input. Moreover, the compiler automatically parallelized the computation, so that each device computed its output shard from its input shard in parallel.\n",
    "\n",
    "In other words, even though we wrote the `jnp.sin` computation as if a single machine were to execute it, the compiler splits up the computation for us and executes it on multiple devices.\n",
    "\n",
    "We can do the same for more than just elementwise operations too. Consider a matrix multiplication with sharded inputs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Dq043GkP3vGQ",
    "outputId": "350219a8-1e4a-4404-fe14-50f97ea3e7ba"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lhs sharding:\n",
      "┌───────────────────────┐\n",
      "│        TPU 0,1        │\n",
      "├───────────────────────┤\n",
      "│        TPU 2,3        │\n",
      "├───────────────────────┤\n",
      "│        TPU 6,7        │\n",
      "├───────────────────────┤\n",
      "│        TPU 4,5        │\n",
      "└───────────────────────┘\n",
      "rhs sharding:\n",
      "┌───────────┬───────────┐\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│TPU 0,2,4,6│TPU 1,3,5,7│\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "└───────────┴───────────┘\n",
      "out sharding:\n",
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, sharding.reshape(4, 2).replicate(1))\n",
    "z = jax.device_put(x, sharding.reshape(4, 2).replicate(0))\n",
    "print('lhs sharding:')\n",
    "jax.debug.visualize_array_sharding(y)\n",
    "print('rhs sharding:')\n",
    "jax.debug.visualize_array_sharding(z)\n",
    "\n",
    "w = jnp.dot(y, z)\n",
    "print('out sharding:')\n",
    "jax.debug.visualize_array_sharding(w)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "_EPNaWzgazft"
   },
   "source": [
    "Here the compiler chose the output sharding so that it could maximally parallelize the computation: without needing communication, each device already has the input shards it needs to compute its output shard.\n",
    "\n",
    "How can we be sure it's actually running in parallel? We can do a simple timing experiment:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "QjQ5u8qh3vGQ",
    "outputId": "bd29edcd-b87c-486e-c568-906f06ae16be"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────────────────┐\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│         TPU 0         │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "x_single = jax.device_put(x, jax.devices()[0])\n",
    "jax.debug.visualize_array_sharding(x_single)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8tn8lOj73vGR",
    "outputId": "5809b3c8-7333-4cd3-db97-a7aede943dce"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.allclose(jnp.dot(x_single, x_single),\n",
    "            jnp.dot(y, z))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "D7PpZwhR3vGR",
    "outputId": "4f0bd43d-0b32-4089-d3da-c8f1449e3526"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 loops, best of 5: 19.3 ms per loop\n"
     ]
    }
   ],
   "source": [
    "%timeit -n 5 -r 5 jnp.dot(x_single, x_single).block_until_ready()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "rgo_yVHF3vGR",
    "outputId": "97f19052-f1c9-4d30-f453-07b3a7208aa9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 loops, best of 5: 3.25 ms per loop\n"
     ]
    }
   ],
   "source": [
    "%timeit -n 5 -r 5 jnp.dot(y, z).block_until_ready()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "gglQIMXJnnJw"
   },
   "source": [
    "Even copying a sharded `Array` produces a result with the sharding of the input:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "f1Zw-2lH3vGR",
    "outputId": "a796bed4-07b0-497d-8fd8-31a22ab9762e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n"
     ]
    }
   ],
   "source": [
    "w_copy = jnp.copy(w)\n",
    "jax.debug.visualize_array_sharding(w_copy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3qfPjJdhgerc"
   },
   "source": [
    "So computation follows data placement: when we explicitly shard data with `jax.device_put`, and apply functions to that data, the compiler attempts to parallelize the computation and decide the output sharding. This policy for sharded data is a generalization of [JAX's policy of following explicit device placement](https://jax.readthedocs.io/en/latest/faq.html#controlling-data-and-computation-placement-on-devices)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "QRB95LaWuT80"
   },
   "source": [
    "### When explicit shardings disagree, JAX errors\n",
    "\n",
    "But what if two arguments to a computation are explicitly placed on different sets of devices, or with incompatible device orders?\n",
    "In these ambiguous cases, an error is raised:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1vAkZAOY3vGR"
   },
   "outputs": [],
   "source": [
    "import textwrap\n",
    "from termcolor import colored\n",
    "\n",
    "def print_exception(e):\n",
    "  name = colored(f'{type(e).__name__}', 'red')\n",
    "  print(textwrap.fill(f'{name}: {str(e)}'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "DHh0N3vn3vGS",
    "outputId": "e7741882-0ebf-4237-e5d1-e48c9b9c178f"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31mValueError\u001b[0m: Devices of all `Array` inputs and outputs should\n",
      "be the same. Got array device ids [0, 1, 2, 3] on platform TPU and\n",
      "another array's device ids [4, 5, 6, 7] on platform TPU\n"
     ]
    }
   ],
   "source": [
    "sharding1 = PositionalSharding(jax.devices()[:4])\n",
    "sharding2 = PositionalSharding(jax.devices()[4:])\n",
    "\n",
    "y = jax.device_put(x, sharding1.reshape(2, 2))\n",
    "z = jax.device_put(x, sharding2.reshape(2, 2))\n",
    "try: y + z\n",
    "except ValueError as e: print_exception(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Im7DkoOl3vGS",
    "outputId": "3adfe1cb-db52-4a9d-e98e-62c6455c3100"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31mValueError\u001b[0m: Devices of all `Array` inputs and outputs should\n",
      "be the same. Got array device ids [0, 1, 2, 3, 4, 5, 6, 7] on platform\n",
      "TPU and another array's device ids [0, 1, 2, 3, 6, 7, 4, 5] on\n",
      "platform TPU\n"
     ]
    }
   ],
   "source": [
    "devices = jax.devices()\n",
    "permuted_devices = [devices[i] for i in [0, 1, 2, 3, 6, 7, 4, 5]]\n",
    "\n",
    "sharding1 = PositionalSharding(devices)\n",
    "sharding2 = PositionalSharding(permuted_devices)\n",
    "\n",
    "y = jax.device_put(x, sharding1.reshape(4, 2))\n",
    "z = jax.device_put(x, sharding2.reshape(4, 2))\n",
    "try: y + z\n",
    "except ValueError as e: print_exception(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6ZYcK8eXrn0p"
   },
   "source": [
    "We say arrays that have been explicitly placed or sharded with `jax.device_put` are _committed_ to their device(s), and so won't be automatically moved. See the [device placement FAQ](https://jax.readthedocs.io/en/latest/faq.html#controlling-data-and-computation-placement-on-devices) for more information.\n",
    "\n",
    "When arrays are _not_ explicitly placed or sharded with `jax.device_put`, they are placed _uncommitted_ on the default device.\n",
    "Unlike committed arrays, uncommitted arrays can be moved and resharded automatically: that is, uncommitted arrays can be arguments to a computation even if other arguments are explicitly placed on different devices.\n",
    "\n",
    "For example, the output of `jnp.zeros`, `jnp.arange`, and `jnp.array` are uncommitted:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "_QvtKL8r3vGS",
    "outputId": "e0078805-bdfd-436e-f94f-7cd256d2574f"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "no error!\n"
     ]
    }
   ],
   "source": [
    "y = jax.device_put(x, sharding1.reshape(4, 2))\n",
    "y + jnp.ones_like(y)\n",
    "y + jnp.arange(y.size).reshape(y.shape)\n",
    "print('no error!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dqMKl79NaIWF"
   },
   "source": [
    "## Constraining shardings of intermediates in `jit`ted code"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "g4LrDDcJwkHc"
   },
   "source": [
    "While the compiler will attempt to decide how a function's intermediate values and outputs should be sharded, we can also give it hints using `jax.lax.with_sharding_constraint`. Using `jax.lax.with_sharding_constraint` is much like `jax.device_put`, except we use it inside staged-out (i.e. `jit`-decorated) functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "jniSFm5V3vGT"
   },
   "outputs": [],
   "source": [
    "sharding = PositionalSharding(mesh_utils.create_device_mesh((8,)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Q1wuDp-L3vGT"
   },
   "outputs": [],
   "source": [
    "x = jax.random.normal(jax.random.key(0), (8192, 8192))\n",
    "x = jax.device_put(x, sharding.reshape(4, 2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "rqEDj0wB3vGT"
   },
   "outputs": [],
   "source": [
    "@jax.jit\n",
    "def f(x):\n",
    "  x = x + 1\n",
    "  y = jax.lax.with_sharding_constraint(x, sharding.reshape(2, 4))\n",
    "  return y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "zYFS-n4r3vGT",
    "outputId": "d23a7938-cb7d-44b4-b9c7-83edf1d1145e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n",
      "┌───────┬───────┬───────┬───────┐\n",
      "│       │       │       │       │\n",
      "│ TPU 0 │ TPU 1 │ TPU 2 │ TPU 3 │\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "├───────┼───────┼───────┼───────┤\n",
      "│       │       │       │       │\n",
      "│ TPU 6 │ TPU 7 │ TPU 4 │ TPU 5 │\n",
      "│       │       │       │       │\n",
      "│       │       │       │       │\n",
      "└───────┴───────┴───────┴───────┘\n"
     ]
    }
   ],
   "source": [
    "jax.debug.visualize_array_sharding(x)\n",
    "y = f(x)\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8g_2Y8wp3vGT"
   },
   "outputs": [],
   "source": [
    "@jax.jit\n",
    "def f(x):\n",
    "  x = x + 1\n",
    "  y = jax.lax.with_sharding_constraint(x, sharding.replicate())\n",
    "  return y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "AiRFtVsR3vGT",
    "outputId": "f3e28a70-46cf-46fb-c801-82f0ddb447e4"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌──────────┬──────────┐\n",
      "│  TPU 0   │  TPU 1   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 2   │  TPU 3   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 6   │  TPU 7   │\n",
      "├──────────┼──────────┤\n",
      "│  TPU 4   │  TPU 5   │\n",
      "└──────────┴──────────┘\n",
      "┌───────────────────────┐\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│  TPU 0,1,2,3,4,5,6,7  │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "│                       │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "jax.debug.visualize_array_sharding(x)\n",
    "y = f(x)\n",
    "jax.debug.visualize_array_sharding(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "_Y1P5wLTzJSz"
   },
   "source": [
    "By adding `with_sharding_constraint`, we've constrained the sharding of the output. In addition to respecting the annotation on a particular intermediate, the compiler will use annotations to decide shardings for other values.\n",
    "\n",
    "It's often a good practice to annotate the outputs of computations, for example based on how the values are ultimately consumed."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "QUkXWG-baMUs"
   },
   "source": [
    "## Examples: neural networks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "g7y0OJBSGoSW"
   },
   "source": [
    "**⚠️ WARNING: The following is meant to be a simple demonstration of automatic sharding propagation with `jax.Array`, but it may not reflect best practices for real examples.** For instance, real examples may require more use of `with_sharding_constraint`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3ii_UPkG3gzP"
   },
   "source": [
    "We can use `jax.device_put` and `jax.jit`'s computation-follows-sharding features to parallelize computation in neural networks. Here are some simple examples, based on this basic neural network:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "mEKF3zIF3vGU"
   },
   "outputs": [],
   "source": [
    "import jax\n",
    "import jax.numpy as jnp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Mocs3oGe3vGU"
   },
   "outputs": [],
   "source": [
    "def predict(params, inputs):\n",
    "  for W, b in params:\n",
    "    outputs = jnp.dot(inputs, W) + b\n",
    "    inputs = jnp.maximum(outputs, 0)\n",
    "  return outputs\n",
    "\n",
    "def loss(params, batch):\n",
    "  inputs, targets = batch\n",
    "  predictions = predict(params, inputs)\n",
    "  return jnp.mean(jnp.sum((predictions - targets)**2, axis=-1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "glBB8tzW3vGU"
   },
   "outputs": [],
   "source": [
    "loss_jit = jax.jit(loss)\n",
    "gradfun = jax.jit(jax.grad(loss))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "R0x62AIa3vGU"
   },
   "outputs": [],
   "source": [
    "def init_layer(key, n_in, n_out):\n",
    "    k1, k2 = jax.random.split(key)\n",
    "    W = jax.random.normal(k1, (n_in, n_out)) / jnp.sqrt(n_in)\n",
    "    b = jax.random.normal(k2, (n_out,))\n",
    "    return W, b\n",
    "\n",
    "def init_model(key, layer_sizes, batch_size):\n",
    "    key, *keys = jax.random.split(key, len(layer_sizes))\n",
    "    params = list(map(init_layer, keys, layer_sizes[:-1], layer_sizes[1:]))\n",
    "\n",
    "    key, *keys = jax.random.split(key, 3)\n",
    "    inputs = jax.random.normal(keys[0], (batch_size, layer_sizes[0]))\n",
    "    targets = jax.random.normal(keys[1], (batch_size, layer_sizes[-1]))\n",
    "\n",
    "    return params, (inputs, targets)\n",
    "\n",
    "layer_sizes = [784, 8192, 8192, 8192, 10]\n",
    "batch_size = 8192\n",
    "\n",
    "params, batch = init_model(jax.random.key(0), layer_sizes, batch_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "sJv_h0AS2drh"
   },
   "source": [
    "### 8-way batch data parallelism"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "_Q5NbdOn3vGV"
   },
   "outputs": [],
   "source": [
    "sharding = PositionalSharding(jax.devices()).reshape(8, 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "3KC6ieEe3vGV"
   },
   "outputs": [],
   "source": [
    "batch = jax.device_put(batch, sharding)\n",
    "params = jax.device_put(params, sharding.replicate())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "MUb-QE2b3vGV",
    "outputId": "1f831ea5-5a30-49ad-8195-977ff7ed476a"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Array(23.469475, dtype=float32)"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "loss_jit(params, batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "HUkw0u413vGV",
    "outputId": "dfa2599c-9440-4657-9035-0dc3bbf625e1"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10.760101\n"
     ]
    }
   ],
   "source": [
    "step_size = 1e-5\n",
    "\n",
    "for _ in range(30):\n",
    "  grads = gradfun(params, batch)\n",
    "  params = [(W - step_size * dW, b - step_size * db)\n",
    "            for (W, b), (dW, db) in zip(params, grads)]\n",
    "\n",
    "print(loss_jit(params, batch))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "paCw6Zaj3vGV",
    "outputId": "8ab1c32c-f2b1-465c-df71-f5a599e7f19e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 loops, best of 5: 26.3 ms per loop\n"
     ]
    }
   ],
   "source": [
    "%timeit -n 5 -r 5 gradfun(params, batch)[0][0].block_until_ready()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "BF86UWpg3vGV"
   },
   "outputs": [],
   "source": [
    "batch_single = jax.device_put(batch, jax.devices()[0])\n",
    "params_single = jax.device_put(params, jax.devices()[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Z1wgUKXk3vGV",
    "outputId": "74df8892-c349-41dc-cb1b-e0843ec5c994"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 loops, best of 5: 122 ms per loop\n"
     ]
    }
   ],
   "source": [
    "%timeit -n 5 -r 5 gradfun(params_single, batch_single)[0][0].block_until_ready()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3AjeeB7B4NP6"
   },
   "source": [
    "### 4-way batch data parallelism and 2-way model tensor parallelism"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "N5-zzgW03vGW"
   },
   "outputs": [],
   "source": [
    "sharding = sharding.reshape(4, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "sgIWCjJK3vGW",
    "outputId": "b2fdc556-05cc-4e68-fa04-48643d194dee"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────┐\n",
      "│TPU 0,1│\n",
      "├───────┤\n",
      "│TPU 2,3│\n",
      "├───────┤\n",
      "│TPU 4,5│\n",
      "├───────┤\n",
      "│TPU 6,7│\n",
      "└───────┘\n",
      "┌───────┐\n",
      "│TPU 0,1│\n",
      "├───────┤\n",
      "│TPU 2,3│\n",
      "├───────┤\n",
      "│TPU 4,5│\n",
      "├───────┤\n",
      "│TPU 6,7│\n",
      "└───────┘\n"
     ]
    }
   ],
   "source": [
    "batch = jax.device_put(batch, sharding.replicate(1))\n",
    "jax.debug.visualize_array_sharding(batch[0])\n",
    "jax.debug.visualize_array_sharding(batch[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "BqCjYCgg3vGW"
   },
   "outputs": [],
   "source": [
    "(W1, b1), (W2, b2), (W3, b3), (W4, b4) = params\n",
    "\n",
    "W1 = jax.device_put(W1, sharding.replicate())\n",
    "b1 = jax.device_put(b1, sharding.replicate())\n",
    "\n",
    "W2 = jax.device_put(W2, sharding.replicate(0))\n",
    "b2 = jax.device_put(b2, sharding.replicate(0))\n",
    "\n",
    "W3 = jax.device_put(W3, sharding.replicate(0).T)\n",
    "b3 = jax.device_put(b3, sharding.replicate())\n",
    "\n",
    "W4 = jax.device_put(W4, sharding.replicate())\n",
    "b4 = jax.device_put(b4, sharding.replicate())\n",
    "\n",
    "params = (W1, b1), (W2, b2), (W3, b3), (W4, b4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "_lSJ63sh3vGW",
    "outputId": "5b37aa8b-3226-4805-8282-876e8d06edda"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────┬───────────┐\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│TPU 0,2,4,6│TPU 1,3,5,7│\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "└───────────┴───────────┘\n"
     ]
    }
   ],
   "source": [
    "jax.debug.visualize_array_sharding(W2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "fxkfWYkk3vGW",
    "outputId": "8a1063c3-540b-47c1-d990-a6845da861f7"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────────────────┐\n",
      "│                       │\n",
      "│      TPU 0,2,4,6      │\n",
      "│                       │\n",
      "│                       │\n",
      "├───────────────────────┤\n",
      "│                       │\n",
      "│      TPU 1,3,5,7      │\n",
      "│                       │\n",
      "│                       │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "jax.debug.visualize_array_sharding(W3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "uPCVs-_k3vGW",
    "outputId": "de01cdfc-36cb-4823-c692-22c692ef4220"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10.760103\n"
     ]
    }
   ],
   "source": [
    "print(loss_jit(params, batch))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "L9JebLK_3vGW"
   },
   "outputs": [],
   "source": [
    "step_size = 1e-5\n",
    "\n",
    "for _ in range(30):\n",
    "    grads = gradfun(params, batch)\n",
    "    params = [(W - step_size * dW, b - step_size * db)\n",
    "              for (W, b), (dW, db) in zip(params, grads)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "c9Sbl69e3vGX",
    "outputId": "8272c5fa-e59f-4953-c2d5-658c42a28712"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10.752466\n"
     ]
    }
   ],
   "source": [
    "print(loss_jit(params, batch))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "lkAF0dAb3vGX",
    "outputId": "acf0df31-c5e1-4683-b73f-b0cd1b0929f8"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────────┬───────────┐\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│TPU 0,2,4,6│TPU 1,3,5,7│\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "│           │           │\n",
      "└───────────┴───────────┘\n",
      "┌───────────────────────┐\n",
      "│                       │\n",
      "│      TPU 0,2,4,6      │\n",
      "│                       │\n",
      "│                       │\n",
      "├───────────────────────┤\n",
      "│                       │\n",
      "│      TPU 1,3,5,7      │\n",
      "│                       │\n",
      "│                       │\n",
      "└───────────────────────┘\n"
     ]
    }
   ],
   "source": [
    "(W1, b1), (W2, b2), (W3, b3), (W4, b4) = params\n",
    "jax.debug.visualize_array_sharding(W2)\n",
    "jax.debug.visualize_array_sharding(W3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "I1Npor3i3vGX",
    "outputId": "4099f6dd-7b46-4123-c1cb-5173c3d3278e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 loops, best of 10: 30.5 ms per loop\n"
     ]
    }
   ],
   "source": [
    "%timeit -n 10 -r 10 gradfun(params, batch)[0][0].block_until_ready()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3diqi5VRBy6S"
   },
   "source": [
    "## Sharp bits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OTfoXNnxFYDJ"
   },
   "source": [
    "### Generating random numbers\n",
    "\n",
    "JAX comes with a functional, deterministic [random number generator](https://jax.readthedocs.io/en/latest/jep/263-prng.html). It underlies the various sampling functions in the [`jax.random` module](https://jax.readthedocs.io/en/latest/jax.random.html), such as `jax.random.uniform`.\n",
    "\n",
    "JAX's random numbers are produced by a counter-based PRNG, so in principle, random number generation should be a pure map over counter values. A pure map is a trivially partitionable operation in principle. It should require no cross-device communication, nor any redundant computation across devices.\n",
    "\n",
    "However, the existing stable RNG implementation is not automatically partitionable, for historical reasons."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ht_zYFVXNrjN"
   },
   "source": [
    "Consider the following example, where a function draws random uniform numbers and adds them to the input, elementwise:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "kwS-aQE_3vGX"
   },
   "outputs": [],
   "source": [
    "@jax.jit\n",
    "def f(key, x):\n",
    "  numbers = jax.random.uniform(key, x.shape)\n",
    "  return x + numbers\n",
    "\n",
    "key = jax.random.key(42)\n",
    "x_sharding = jax.sharding.PositionalSharding(jax.devices())\n",
    "x = jax.device_put(jnp.arange(24), x_sharding)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ZgSA9x9NLMaP"
   },
   "source": [
    "On a partitioned input, the function `f` produces output that is also partitioned:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Oi97rpLz3vGY",
    "outputId": "204a7e8d-dc88-4b77-b7e3-0e72f306c5d3"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐\n",
      "│ TPU 0 │ TPU 1 │ TPU 2 │ TPU 3 │ TPU 4 │ TPU 5 │ TPU 6 │ TPU 7 │\n",
      "└───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘\n"
     ]
    }
   ],
   "source": [
    "jax.debug.visualize_array_sharding(f(key, x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WnjlWDUYLkp6"
   },
   "source": [
    "But if we inspect the compiled computation for `f` on this partitioned input, we see that it does involve some communication:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "64wIZuSJ3vGY",
    "outputId": "1054fe99-0476-44ec-9693-b0d8f98bf6a8"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Communicating? True\n"
     ]
    }
   ],
   "source": [
    "f_exe = f.lower(key, x).compile()\n",
    "print('Communicating?', 'collective-permute' in f_exe.as_text())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "AXp9i8fbL8DD"
   },
   "source": [
    "One way to work around this is to configure JAX with the experimental upgrade flag `jax_threefry_partitionable`. With the flag on, the \"collective permute\" operation is now gone from the compiled computation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1I7bqxA63vGY",
    "outputId": "ec4c579d-f446-4b48-ceda-785c09ba299b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Communicating? False\n"
     ]
    }
   ],
   "source": [
    "jax.config.update('jax_threefry_partitionable', True)\n",
    "f_exe = f.lower(key, x).compile()\n",
    "print('Communicating?', 'collective-permute' in f_exe.as_text())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WV8ZccM5SXOU"
   },
   "source": [
    "The output is still partitioned:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "zHPJzdn23vGY",
    "outputId": "a8904d20-4d04-4f59-8eae-281e47d29246"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "┌───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐\n",
      "│ TPU 0 │ TPU 1 │ TPU 2 │ TPU 3 │ TPU 4 │ TPU 5 │ TPU 6 │ TPU 7 │\n",
      "└───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘\n"
     ]
    }
   ],
   "source": [
    "jax.debug.visualize_array_sharding(f(key, x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "kaK--hPmSPpV"
   },
   "source": [
    "One caveat to the `jax_threefry_partitionable` option, however, is that _the random values produced may be different than without the flag set_, even though they were generated by the same random key:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "nBUHBBal3vGY",
    "outputId": "f194c213-0688-4b7a-ffb8-c4453b82b1f1"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Stable:\n",
      "[ 0.72503686  1.8532515   2.983416    3.083253    4.0332246   5.4782867\n",
      "  6.1720605   7.6900277   8.602836    9.810046   10.861367   11.907651\n",
      " 12.330483   13.456195   14.808557   15.960099   16.067581   17.739723\n",
      " 18.335474   19.46401    20.390276   21.116539   22.858128   23.223194  ]\n",
      "\n",
      "Partitionable:\n",
      "[ 0.48870957  1.6797972   2.6162715   3.561016    4.4506445   5.585866\n",
      "  6.0748096   7.775133    8.698959    9.818634   10.350306   11.87282\n",
      " 12.925881   13.86013    14.477554   15.818481   16.711355   17.586697\n",
      " 18.073738   19.777622   20.404566   21.119123   22.026257   23.63918   ]\n"
     ]
    }
   ],
   "source": [
    "jax.config.update('jax_threefry_partitionable', False)\n",
    "print('Stable:')\n",
    "print(f(key, x))\n",
    "print()\n",
    "\n",
    "jax.config.update('jax_threefry_partitionable', True)\n",
    "print('Partitionable:')\n",
    "print(f(key, x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8BDPqgOrTMfK"
   },
   "source": [
    "In `jax_threefry_partitionable` mode, the JAX PRNG remains deterministic, but its implementation is new (and under development). The random values generated for a given key will be the same at a given JAX version (or a given commit on the `main` branch), but may vary across releases."
   ]
  }
 ],
 "metadata": {
  "accelerator": "TPU",
  "colab": {
   "provenance": [],
   "toc_visible": true
  },
  "gpuClass": "standard",
  "jupytext": {
   "formats": "ipynb,md:myst"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
